package com.skylin.mysell.controller;

import com.skylin.mysell.VO.ProductInfoVO;
import com.skylin.mysell.VO.ProductVO;
import com.skylin.mysell.VO.ResultVO;
import com.skylin.mysell.entities.ProductCategory;
import com.skylin.mysell.entities.ProductInfo;
import com.skylin.mysell.service.ProductCategoryService;
import com.skylin.mysell.service.ProductInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author quanlinlin on 2018/12/15 17:23.
 * @version 1.0
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {


    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @GetMapping("/list")
    public ResultVO list() {
        /**
         * 1.查询所有上架商品
         * 2.查询类目
         * 3.数据拼装
         */

        List<ProductInfo> productInfoList = productInfoService.findUpAll();
        ArrayList<Integer> typeList = productInfoList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toCollection(ArrayList::new));
        List<ProductCategory> categoryList = productCategoryService.findByCategoryTypeIn(typeList);

        ArrayList<ProductVO> productVOArrayList = new ArrayList<>();
        for (ProductCategory productCategory : categoryList) {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(productCategory, productVO);

            ArrayList<ProductInfoVO> productInfoVOS = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList) {
                if (Objects.equals(productInfo.getCategoryType(), productVO.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOS.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOS);
            productVOArrayList.add(productVO);
        }


        ResultVO<Object> resultVO = new ResultVO<>();
        resultVO.setCode(0);
        resultVO.setMessage("成功");
        resultVO.setData(productVOArrayList);
        return resultVO;
    }
}
